var fs = require("fs");
var iconv = require("iconv-lite");
const { exec } = require('child_process');
const { execFile } = require('child_process')
var path = require("path")

// 将csb每一行转换成数组中的元素
var lines = []
// 检查csv文件
let resourcesFilePath = path.join(process.cwd(), '/resources/')

// console.log(resourcesFilePath)
// let csvFile = path.join(resourcesFilePath, 'words.csv')
let csvFile = 'words.csv'
try {
  fs.readFileSync(csvFile, { encoding: "binary" });
} catch (err) {
  // 出错了
  fs.writeFileSync(
    csvFile,
    '',
    (error) => { }
  );
}

// 读取csv文件
var fileStr = fs.readFileSync(csvFile, { encoding: "binary" });
var buf = new Buffer.from(fileStr, "binary");
var str = iconv.decode(buf, "gbk");
console.log(str.split("\r\n"));
lines = str.split("\r\n");
if (lines[0] == '') {
  lines = ['0,hello add your words,']
} else {
  // 去除最后一个空行
  lines.pop()
}
console.log(lines);
// 状态栏
var span_total = this.document.querySelector('#total')
span_total.innerHTML = lines.length

// 已查看多的单词个数
var span_watched = this.document.querySelector('#watched')
// 需要回顾的单词个数
var span_need = this.document.querySelector('#need')

// 记录所有查看过的单词的下标
var all_watched_index = []
// 单词下标
let nowIndex = 0

// 更新已查看单词的个数
function updateWatched() {
  span_watched.innerHTML = all_watched_index.length
}

// 获取单词本里的新单词
// 看过的不再显示
// 已经看过单词个数
let count = 0

// 判断单词是否看过，看过重新获取单词
function getNewWord() {
  // 可查看的个数
  var lines_need = lines.filter(item => {
    console.log(item);
    if (item.split(',')[0] * 1 >= 5) {
      console.log('>=5');
      return false
    }
    if (Boolean(item.split(',')[3]) == false) {
      console.log('undefined');
      return true
    }
    if ((Date.now() - new Date(item.split(",")[3]).getTime()) > 5 * 60 * 1000) {
      console.log('>5 * 60 * 1000');
      return true
    }
    return false
  })
  span_need.innerHTML = lines_need.length

  // 随机单词
  nowIndex = (Math.random() * lines.length + '').split('.')[0] * 1
  // 随机数[0, lines.length)]
  console.log("nowIndex:", nowIndex);

  // 获取上次见到的时间
  var old_time = lines[nowIndex].split(",")[3];
  console.log("上次记忆的时间：", old_time);
  // 没有记录时间的
  // a='0,new,新的'.split(',')[3]
  // undefined
  if (Boolean(old_time) == false) {
    all_watched_index.push(nowIndex)
    all_watched_index.sort(function (a, b) { return a - b })
    console.log('all_watched_index:', all_watched_index)
    // 更新查看单词的个数
    updateWatched()
    return lines[nowIndex].split(",")[1];
  }
  // 有记录时间的
  // a='2,time,时间,2022/1/27 5:52'.split(',')[3]
  // '2022/1/27 5:52'
  var cost_time = Date.now() - new Date(old_time).getTime()
  console.log("已过去毫秒值：", cost_time);
  console.log("已过去：",
    ((((new Date().getTime() - new Date(old_time)) + '').slice(0, -3) * 1 / 60 + '').split('.')[0] * 1 / 60 + '').split('.')[0] * 1, "小时",
    ((((new Date().getTime() - new Date(old_time)) + '').slice(0, -3) * 1 / 60 + '').split('.')[0] * 1 % 60 + '').split('.')[0] * 1, "分",
    (((new Date().getTime() - new Date(old_time)) + '').slice(0, -3) * 1 % 60 + '').split('.')[0] * 1, "秒",
  );
  // 已经过去的毫秒值
  var time_interval = 5 * 60 * 1000;
  if (cost_time >= time_interval) {
    all_watched_index.push(nowIndex)
    all_watched_index.sort(function (a, b) { return a - b })
    console.log('all_watched_index:', all_watched_index)
    // 更新查看单词的个数
    updateWatched()
    return lines[nowIndex].split(",")[1];
  }
  // 今天看过的
  if (all_watched_index.includes(nowIndex)) {
    // 重新获取值
    // 不写死循环
    for (var i = 0; i < 10000; i++) {
      nowIndex = (Math.random() * lines.length + '').split('.')[0] * 1
      if (i == 9999) {
        var option = {
          title: "需要认识的单词-已经看完",
          body: "稍后再来吧",
        };
        new window.Notification(option.title, option);
      }
      if (all_watched_index.includes(nowIndex)) {
        continue
      } else {
        all_watched_index.push(nowIndex)
        all_watched_index.sort(function (a, b) { return a - b })
        console.log('all_watched_index:', all_watched_index)
        // 更新查看单词的个数
        updateWatched()
        return lines[nowIndex].split(",")[1]
        break
      }
    };
  }
  all_watched_index.sort(function (a, b) { return a - b })
  console.log('all_watched_index:', all_watched_index)
  this.document.querySelector('#word_chinese').innerHTML = ''
  return '已查看所有需要查看的单词'
}

// 初始化
// 设置页面显示
var h1_word = this.document.querySelector('#word')
// querySelector 返回匹配到选择器的第一个节点
h1_word.innerHTML = getNewWord()
var input_enter_content = this.document.querySelector('#enter_content')
// 光标聚焦在输入框
input_enter_content.focus()


var btn_error = this.document.querySelector('#error')
var h1_word_chinese = this.document.querySelector('#word_chinese')

// 点击不知道按钮
btn_error.onclick = function () {
  console.log("I don't know");
  // 显示英文和意思
  h1_word_chinese.innerHTML = lines[nowIndex].split(",")[1] + ':' + lines[nowIndex].split(",")[2]
  h1_word_chinese.className = 'infor-error'
  // 更新单词记录
  lines[nowIndex] = '0,' + lines[nowIndex].split(",")[1] + ',' + lines[nowIndex].split(",")[2] + ',' +
    new Date().toLocaleDateString() + " " + new Date().getHours() + ":" + new Date().getMinutes();
  // 显示下一个单词
  h1_word.innerHTML = getNewWord()
  // 看过的不显示
}

// 输入单词意思，检查是否正确的逻辑
function handleSuccess() {
  console.log('I kown it');
  if (input_enter_content.value.replace(' ', '') == '') {
    h1_word_chinese.innerHTML = '输入框不能为空'
    h1_word_chinese.className = 'infor-warning'
    input_enter_content.focus()
    console.log('输入框不能为空')
    return ''
  }
  if (lines[nowIndex].split(',')[2] == input_enter_content.value) {
    console.log("回答正确");
    // 显示意思和中文
    h1_word_chinese.innerHTML = lines[nowIndex].split(",")[2] + ':' + lines[nowIndex].split(",")[1]
    h1_word_chinese.className = 'infor-success'
    lines[nowIndex] = lines[nowIndex].split(",")[0] * 1 + 1 + "," + lines[nowIndex].split(",")[1] + ',' + lines[nowIndex].split(",")[2] + ',' +
      new Date().toLocaleDateString() + " " + new Date().getHours() + ":" + new Date().getMinutes();
    // 显示下一个单词
    h1_word.innerHTML = getNewWord()
    // 输入框置空
    input_enter_content.value = ''
    input_enter_content.focus()
  } else {
    console.log('回答错误');
    // 显示英文和意思
    h1_word_chinese.innerHTML = lines[nowIndex].split(",")[1] + ':' + lines[nowIndex].split(",")[2]
    h1_word_chinese.className = 'infor-error'
    // 更新单词记录
    lines[nowIndex] = '0,' + lines[nowIndex].split(",")[1] + ',' + lines[nowIndex].split(",")[2] + ',' +
      new Date().toLocaleDateString() + " " + new Date().getHours() + ":" + new Date().getMinutes();
    // 显示下一个单词
    h1_word.innerHTML = getNewWord()
    // 输入框置空
    input_enter_content.value = ''
    input_enter_content.focus()
  }
}

// 点击知道按钮
var btn_success = this.document.querySelector('#success')
btn_success.onclick = handleSuccess
// 不能加括号handleSuccess()加括号后就立即执行了


// 添加键盘enter键监听
this.document.onkeydown = function (event) {
  var e = event || window.event || arguments.callee.caller.arguments[0]
  if (e && e.keyCode == 13) {
    // enter
    console.log('enter');
    handleSuccess()
  }
  // 快捷键：Ctrl+s保存
  if (e.keyCode == 83) {
    saveRecord()
  }
}

// 保存回顾记录
function saveRecord() {
  // fs.wirteFile有三个参数
  // 1,第一个参数是要写入的文件路径
  // 2,第二个参数是要写入得内容
  // 3,第三个参数是可选参数,表示要写入的文件编码格式,一般就不写,默认就行
  // 4,第四个参数是个回调函数  只有一个参数error,来判断是否写入成功
  // 如果在使用fs.writeFIle时,要写入文件不存在,则直接写入,如果存在,则会覆盖原内容}

  fs.writeFile(
    csvFile,
    iconv.encode(lines.join("\r\n") + "\r\n", "gbk"),
    (error) => {
      if (error) {
        console.log("写入文件失败,原因是" + error.message);
        var option = {
          title: "保存失败",
          body: "查看是否有其他程序使用文件，比如：wps中打开了该文件",
        };
        new window.Notification(option.title, option);
        myNotification.onclick = function () {
          // 点击了弹框消息
          console.log("文件写入失败");
        };
        return "";
      }
      if (h1_word.innerHTML != '已查看所有需要查看的单词') {

        h1_word_chinese.innerHTML = '查看记录已保存'
        h1_word_chinese.className = 'infor-success'
      }
      console.log("写入成功");
      var option = {
        title: "记录已保存",
        body: "稍后再来吧",
      };
      new window.Notification(option.title, option);
    }
  );
}

// 保存按钮
var btn_save = this.document.querySelector('#save')
btn_save.onclick = saveRecord


var checkbox_searchWord = this.document.querySelector('#searchWord')
var checkbox_addWord = this.document.querySelector('#addWord')
checkbox_addWord.onclick = function () {
  if (checkbox_addWord.checked == true) {
    console.log('开启新增单词功能');
    var exe_ = path.join(resourcesFilePath, 'keyboard.exe')
    execFile(exe_)
    var option = {
      title: "新增单词功能",
      body: "已开启🚀",
    };
    new window.Notification(option.title, option);
  } else {
    console.log('关闭新增单词功能');
    stopExe("keyboard.exe")
    var option = {
      title: "新增单词功能",
      body: "已关闭❌",
    };
    new window.Notification(option.title, option);
  }
}
checkbox_searchWord.onclick = function () {
  if (checkbox_searchWord.checked == true) {
    console.log('开启查询单词功能');
    var exe_ = path.join(resourcesFilePath, 'mouse.exe')
    execFile(exe_)
    var option = {
      title: "查询单词功能",
      body: "已开启🚀",
    };
    new window.Notification(option.title, option);
  } else {
    console.log('关闭查询单词功能');
    stopExe("mouse.exe")
    var option = {
      title: "查询单词功能",
      body: "已关闭❌",
    };
    new window.Notification(option.title, option);
  }
}
// 查看exe是否在运行-start-
const isRunning = (query, cb) => {
  let platform = process.platform;
  let cmd = '';
  switch (platform) {
    case 'win32': cmd = `tasklist`; break;
    case 'darwin': cmd = `ps -ax | grep ${query}`; break;
    case 'linux': cmd = `ps -A`; break;
    default: break;
  }
  exec(cmd, (err, stdout, stderr) => {
    cb(stdout.toLowerCase().indexOf(query.toLowerCase()) > -1);
  });
}
// 查看exe是否在运行-end-

// 关闭exe是否在运行-start-
const stopExe = (exeName) => {
  let platform = process.platform;
  let cmd = '';
  switch (platform) {
    case 'win32': cmd = `taskkill /F /IM ${exeName}`; break;
    default: break;
  }
  exec(cmd);
}
// 关闭exe是否在运行-end-

isRunning('keyboard.exe', (status) => {
  console.log(status); // true|false
  checkbox_addWord.checked = status
})
isRunning('mouse.exe', (status) => {
  console.log(status); // true|false
  checkbox_searchWord.checked = status
})

